package com.tao.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tao.bean.Employee;
import com.tao.bean.Msg;
import com.tao.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /*删除员工
    * 单个删除，多个删除二合一
    * */
    @RequestMapping(value = "/emp/{empIds}",method = RequestMethod.DELETE)
    @ResponseBody
    public Msg deleteEmpById(@PathVariable("empIds")String empIds){
        /*如果是包含-的数组*/
        if (empIds.contains("-")) {
            /*定义List集合，用于批量删除方法的参数*/
            List<Integer> ids=new ArrayList<Integer>();
            /*遍历字符串，生成数组*/
            String[] str_ids = empIds.split("-");
            /*遍历数据，拼装List集合*/
            for (String id : str_ids) {
                /*把字符串id转换Integer后，add入List集合中*/
                ids.add(Integer.parseInt(id));
            }
            /*调用批量删除方法，传入List集合参数*/
            employeeService.deleteEmpsByList(ids);

        }else {
            /*不是数据，执行单个删除*/
            int id = Integer.parseInt(empIds);
            employeeService.deleteEmp(id);

        }

        return Msg.success();
    }

    /*修改员工信息*/
    @RequestMapping(value = "/emp/{empId}",method = RequestMethod.PUT)
    @ResponseBody
    public Msg saveEmp(Employee employee){
        employeeService.updateEmp(employee);
        return Msg.success();
    }



    /*通过id查找员工信息*/
    @RequestMapping(value = "/emp/{id}",method = RequestMethod.GET)
    @ResponseBody
    public Msg getEmp(@PathVariable("id")Integer id){
        Employee employee= employeeService.getEmp(id);
        return Msg.success().add("emp",employee);
    }


    /*判断用户名是否可用*/
    @RequestMapping(value = "/checkHasEmp")
    @ResponseBody
    public Msg checkHasEmp(@RequestParam("empName")String empName){
        String regName ="(^[a-zA-Z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,5}$)";
        /*先判断用户名是否符合表达式*/
        if (!empName.matches(regName)){
            return Msg.fail().add("msg","姓名只能是2~5位中文或6~16位英文数字组合！");
        }
        boolean flag = employeeService.checkHasEmp(empName);
        if (flag){
            return Msg.success().add("msg","用户名可用！");
        }else {
            return Msg.fail().add("msg","用户名重复!");
        }
    }

    /*后端JSR303检验，再保存员工信息*/
    @RequestMapping(value = "/emp",method = RequestMethod.POST)
    @ResponseBody
    public Msg saveEmp(@Valid Employee employee, BindingResult result){
        if(result.hasErrors()){
            /*创建Map集合，把错误字段与错误内容封装返回给前端*/
            Map<String,Object> map=new HashMap<String, Object>();
            /*获取错误信息List集合*/
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                System.out.println("错误信息字段："+fieldError.getField());
                System.out.println("错误内容："+fieldError.getDefaultMessage());
                map.put(fieldError.getField(),fieldError.getDefaultMessage());
            }

            return Msg.fail().add("map",map);
        }else {
            employeeService.saveEmp(employee);
            return Msg.success();
        }

    }

    @RequestMapping("/emps")
    @ResponseBody
    public Msg getEmpsWithJson(@RequestParam(value="pn",defaultValue = "1")Integer pn){
        //查询list前执行分布助手，传入页码、以及每页的大小
        PageHelper.startPage(pn,10);

        List<Employee> emps= employeeService.getAll();
        //分布相关信息由PageInfo通过model交给页面，传入list,也可以再传入连续显示的页数
        PageInfo info=new PageInfo(emps,5);
        return Msg.success().add("info",info);
    }


    @RequestMapping("/emps1")
    public String getEmps(@RequestParam(value="pn",defaultValue = "1")Integer pn, Model model){

        //查询list前执行分布助手，传入页码、以及每页的大小
        PageHelper.startPage(pn,10);

        List<Employee> emps= employeeService.getAll();
        //分布相关信息由PageInfo通过model交给页面，传入list,也可以再传入连续显示的页数
        PageInfo info=new PageInfo(emps,10);
        model.addAttribute("info",info);

        return "list";
    }




}
